package cn.edu.heuet.bnve.fragment;

import androidx.annotation.RequiresApi;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;

import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.os.Vibrator;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

import com.haibin.calendarview.Calendar;
import com.xuexiang.xui.widget.button.SmoothCheckBox;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import cn.edu.heuet.bnve.adapter.ClassAdapter;
import cn.edu.heuet.bnve.MainActivity;
import cn.edu.heuet.bnve.R;
import cn.edu.heuet.bnve.activity.WebActivity;
import cn.edu.heuet.bnve.database.ClassDao;
import cn.edu.heuet.bnve.model.NEUClass;
import cn.edu.heuet.bnve.model.Schedule;
import cn.edu.heuet.bnve.activity.ScheduleActivity.ScheduleDetailActivity;
import cn.edu.heuet.bnve.adapter.ScheduleAdapter;
import cn.edu.heuet.bnve.base.fragment.BaseFragment;
import cn.edu.heuet.bnve.database.ScheduleDao;
import cn.edu.heuet.bnve.databinding.FragmentHomeBinding;
import cn.edu.heuet.bnve.view.group.GroupItemDecoration;
import cn.edu.heuet.bnve.view.group.GroupRecyclerView;
import cn.edu.heuet.bnve.utils.SharepreferencesUtilSystemSettings;
import cn.edu.heuet.bnve.utils.StringUtil;
import cn.edu.heuet.bnve.view.RecyclerItemClickListener;

public class HomeFragment extends BaseFragment {

    private HomeViewModel mViewModel;
    private FragmentHomeBinding binding;
    private ScheduleDao scheduleDao;
    private GroupRecyclerView schedulesRecyclerView;
    private Calendar mCurrentDate;
    private List<Schedule> schedulesCur;
    private TextView mTextMonthDay;
    private TextView mTextYear;
    private ClassDao classDao;
    private List<NEUClass> currentDayClasses;
    private int currentWeek=1;
    private GroupRecyclerView classesRecyclerView;
    private MediaPlayer mediaPlayer;
    private Vibrator vibrator;

    public static HomeFragment newInstance() {
        return new HomeFragment();
    }


    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Override
    protected int getLayoutId() {
        return  R.layout.fragment_home;
    }

    @Override
    protected void initView() {

        if (mRootView!=null) {
            binding = DataBindingUtil.bind(this.mRootView);

            schedulesRecyclerView = binding.recyclerViewSchedules;
            classesRecyclerView = binding.recyclerViewClasses;
            mTextMonthDay = binding.tvMonthDay;
            mTextYear = binding.tvYear;

            //获取今日Calender
            mCurrentDate = getCurrentCalendar();
            mTextYear.setText(String.valueOf(mCurrentDate.getYear()));
            mTextMonthDay.setText(mCurrentDate.getMonth() + "月" + mCurrentDate.getDay() + "日");

            //加载首页button
            binding.itemTodo.itemImage.setImageResource(R.drawable.ic_widget_statelayout);
            binding.itemTodo.itemTvTitle.setText("日程");
            binding.itemTable.itemImage.setImageResource(R.drawable.ic_util_view);
            binding.itemTable.itemTvTitle.setText("课程表");
            binding.itemSetting.itemImage.setImageResource(R.drawable.icon_setting);
            binding.itemSetting.itemTvTitle.setText("设置");

        }
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    protected void initData() {

        //获取今日Schedule
        scheduleDao = new ScheduleDao(mContext);
        schedulesCur = scheduleDao.getDataByDay(mCurrentDate);
        //加载RecycleView
        schedulesRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        schedulesRecyclerView.addItemDecoration(new GroupItemDecoration<String, Schedule>());
        schedulesRecyclerView.setAdapter(new ScheduleAdapter(mContext,schedulesCur));
        schedulesRecyclerView.notifyDataSetChanged();

//        //获取今日Classes
//        loadCurrentWeek();
//        classDao =new ClassDao(mContext);
//        int week = mCurrentDate.getWeek();
//        if(week==0){
//            week=7;
//        }
//        currentDayClasses = classDao.getAll(currentWeek,week);
        //加载RecycleView
        classesRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        classesRecyclerView.addItemDecoration(new GroupItemDecoration<String, Schedule>());
//        classesRecyclerView.setAdapter(new ClassAdapter(mContext,currentDayClasses));
//        classesRecyclerView.notifyDataSetChanged();


    }


    @Override
    protected void initEvent() {
        //recycler点击事件
        schedulesRecyclerView.addOnItemTouchListener(new RecyclerItemClickListener(mContext, new RecyclerItemClickListener.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                if(schedulesCur.get(position).getType()!=-1&&schedulesCur.get(position).getType()!=2) {
                    Intent intent = new Intent(mContext, ScheduleDetailActivity.class);
                    intent.putExtra("schedule", schedulesCur.get(position));
                    startActivity(intent);
                }
            }
            @Override
            public void onLongClick(View view, int posotion) {
                if(schedulesCur.get(posotion).getType()==0||schedulesCur.get(posotion).getType()==1){
                    SmoothCheckBox checkBox = view.findViewById(R.id.cb_complete);
                    Schedule schedule = schedulesCur.get(posotion);
                    if(checkBox.isChecked()){
                        checkBox.setChecked(false,true);
                        schedule.setIsComplete(0);
                    }
                    else{
                        checkBox.setChecked(true,true);
                        schedule.setIsComplete(1);
                    }
                    scheduleDao.updateDataById(schedule.getId(),schedule);
                }
            }
        }));
        binding.itemTodo.itemImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (getActivity() instanceof MainActivity) {
                    MainActivity mainActivity = (MainActivity) getActivity();
                    mainActivity.bind.bnve.setCurrentItem(1);
                }
            }
        });
        binding.itemTable.itemImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (getActivity() instanceof MainActivity) {
                    MainActivity mainActivity = (MainActivity) getActivity();
                    mainActivity.bind.bnve.setCurrentItem(3);
                }
            }
        });
        binding.itemSetting.itemImage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (getActivity() instanceof MainActivity) {
                    MainActivity mainActivity = (MainActivity) getActivity();
                    mainActivity.bind.bnve.setCurrentItem(4);
                }
            }
        });

        binding.ivMenu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (getActivity() instanceof MainActivity) {
                    MainActivity mainActivity = (MainActivity) getActivity();
                    mainActivity.drawerLayout.openDrawer(Gravity.LEFT);
                }
            }
        });

    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mViewModel = new ViewModelProvider(this).get(HomeViewModel.class);
        // TODO: Use the ViewModel
    }

    /*
    生成Fragment时改变menu布局
     */
    @Override
    public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
        menu.clear();
        inflater.inflate(R.menu.menu_home,menu);


    }

    @Override
    /**menu监听事件*/
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {

        }

        return false;
    }

    /**
     * 获取今日Calender
     * @return
     */
    public Calendar getCurrentCalendar(){
        Calendar mCurrentDate;
        mCurrentDate = new Calendar();
        Date d = new Date();
        mCurrentDate.setYear(StringUtil.getDate("yyyy", d));
        mCurrentDate.setMonth(StringUtil.getDate("MM", d));
        mCurrentDate.setDay(StringUtil.getDate("dd", d));
        mCurrentDate.setWeek(StringUtil.getWeek(d));
        mCurrentDate.setCurrentDay(true);
        return mCurrentDate;
    }

    /**
     * 重新加载今日Schedule
     */
    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public void onStart() {
        super.onStart();
        if(scheduleDao!=null) {
            schedulesCur = scheduleDao.getDataByDay(mCurrentDate);
            schedulesRecyclerView.setAdapter(new ScheduleAdapter(mContext, schedulesCur));
        }
        //获取今日Classes
        loadCurrentWeek();
        classDao =new ClassDao(mContext);
        int week = mCurrentDate.getWeek();
        if(week==0){
            week=7;
        }
        currentDayClasses = classDao.getAll(currentWeek,week);
        classesRecyclerView.setAdapter(new ClassAdapter(mContext,currentDayClasses));
        classesRecyclerView.notifyDataSetChanged();
    }


    /**
     * 计算当前周次
     * @param date
     * @return
     */
    private int calcWeek(Date date) {
        long a=(new Date().getTime() - date.getTime()) / (1000 * 3600 * 24 * 7) + 1;
        return (int)a;
    }

    /**
     * 重新加载
     */
    private void loadCurrentWeek(){
        String time = SharepreferencesUtilSystemSettings.getValue(mContext,"table_start_date",null);
        if(time!=null) {
            try {
                SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd");
                Date date = ft.parse(time);
                currentWeek = calcWeek(date);
                if(currentWeek<=0){
                    currentWeek=1;
                }
                if(currentWeek>19){
                    currentWeek=19;
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
    }








}